package com.luxsoft.siipap.em.replica.importadores.cxc;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.luxsoft.siipap.em.service.EMServiceLocator;
import com.luxsoft.siipap.model.Direccion;
import com.luxsoft.siipap.model.core.Cliente;
import com.luxsoft.siipap.service.ServiceLocator2;
import com.luxsoft.siipap.util.DBUtils;

public class ActualizarClientesDeCredito {
	
	public void execute(){
		
		final String hql="from Cliente c where c.credito is null order by c.clave";
		ServiceLocator2.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				ScrollableResults rs=session.createQuery(hql).scroll();
				int buff=20;
				while(rs.next()){
					Cliente c=(Cliente)rs.get()[0];
					System.out.println("Procesando : "+c.getNombre());
					actualizarCliente(c);
					buff++;
					if(buff%20==0){
						session.flush();
						session.clear();
					}
				}
				return null;
			}
			
		});
		
	}
	
	public void actualizarCliente(Cliente c){
		String sql="select * from CLIENTES c where c.CLICLAVE=?";
		List<Map<String, Object>> rows=EMServiceLocator.instance()
			.getSiipapDBFOdbcTemplate()
			.queryForList(sql,new Object[]{c.getClave()});
		if(!rows.isEmpty()){
			Map<String,Object> row=rows.get(0);
			Direccion direccion=new Direccion();
			
			direccion.setCalle((String)row.get("CLICALLE"));
			direccion.setColonia((String)row.get("CLICOLON"));
			direccion.setMunicipio((String)row.get("CLIDELEG"));
			direccion.setCp((String)row.get("CLIPOSTAL"));
			
			c.setDireccionFiscal(direccion);
			System.out.println(rows);
			String telefono1=(String)row.get("CLITEL1");
			telefono1=StringUtils.substring(telefono1, 0, 29);
			c.agregarTelefono("TEL1", telefono1);
			
			String rfc=(String)row.get("CLIRFC");
			c.setRfc(rfc);
		}
 	}
	
	
	public static void main(String[] args) {
		DBUtils.whereWeAre();
		new ActualizarClientesDeCredito().execute();
		
	}

}
